var Sequelize = require('sequelize');
var sequelize = require('../../../core/sequlize_pool').sequelize;
var models = require('../../models');
var roleDao = module.exports;

roleDao.createRole = async function(role) {
    return models.admin.AdminRole.create(role);
};

roleDao.updateRole = async function(role) {
    return models.admin.AdminRole.update(role, {
        where: {
            role_id: role.role_id
        }
    });
};

roleDao.getRoleById = async function (roleId){
    return models.admin.AdminRole.findOne({
        where: {
            role_id: roleId,
            is_del: 0
        }
    });
};

roleDao.getRoleByName = async function(roleName) {
    return models.admin.AdminRole.findOne({
        where: {
            role_name: roleName,
            is_del: 0
        }
    });
};

roleDao.getAllRoles = async function () {
    return models.admin.AdminRole.findAll({
        where: {
            is_del: 0
        }
    });
};

roleDao.getRoles = async function (keywords, offset, limit) {
    var where = {is_del:0};
    if (keywords && keywords.length != 0) {
        where = {
            is_del: 0,
            [Sequelize.Op.or]: [
                {
                    role_name: {
                        [Sequelize.Op.like]: '%'+keywords.trim()+'%'
                    }
                }, {
                    description: {
                        [Sequelize.Op.like]: '%'+keywords.trim()+'%'
                    }
                }
            ]
        };
    }
    return models.admin.AdminRole.findAndCountAll({
        where: where,
        order: [['role_id', 'DESC']],
        offset: Number(offset),
        limit: Number(limit),
    });
};

roleDao.destroyRoles = async function (pks) {
    return models.admin.AdminRole.destroyRoles(pks);
};

roleDao.setMenus = async function (role_id, menu_ids) {
    const role = await models.admin.AdminRole.findOne({
        where: {
            role_id: role_id,
            is_del: 0
        }
    });
    const menus = await models.admin.AdminMenu.findAll({
        where: {
            menu_id: menu_ids,
            is_del: 0
        }
    });
    return role.setMenus(menus);
};

roleDao.getMenus = async function (role_id){
    var sql = "SELECT menu.* FROM system_menu AS menu INNER JOIN system_menu_role AS menu_role " +
              "ON menu.menu_id = menu_role.menu_id AND menu.is_del = 0 AND menu_role.role_id = $role_id";
    return sequelize.query(sql, {
        bind: { role_id: role_id },
        type: sequelize.QueryTypes.SELECT,
        model: models.admin.AdminMenu
    });

    // const role = await models.admin.Role.findOne({
    //     where: {
    //         role_id: role_id,
    //         is_del: 0
    //     }
    // });
    // return role.getMenus();
};